package com.jj.network.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * OKHttp封装
 *
 * @param
 */
public class StringCall implements Callback {

	private static final String TAG = "StringCall";
	private static final int CALLBACK_SUCCESSFUL = 0x01;
	private static final int CALLBACK_FAILED = 0x02;

	private static class UIHandler extends Handler {
		private StringCall mCall;

		private UIHandler(StringCall callback) {
			super(Looper.getMainLooper());
			mCall = callback;
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case CALLBACK_SUCCESSFUL: {
					String str = (String) msg.obj;
					if (mCall != null) {
						mCall.onSuccess(str);
						mCall.onEnd();
					}
					break;
				}
				case CALLBACK_FAILED: {
					String e = (String) msg.obj;
					if (mCall != null) {
						mCall.onError(e);
						mCall.onEnd();
					}
					break;
				}
				default:
					super.handleMessage(msg);
					break;
			}

		}
	}

	private final Handler mHandler = new UIHandler(this);

	@Override
	public void onFailure(Call call, IOException e) {
		Message message = Message.obtain();
		message.what = CALLBACK_FAILED;
		message.obj = e.getMessage();
		mHandler.sendMessage(message);
		Log.e(TAG, e+"***"+call.request().headers().toString());
	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {
		Log.e(TAG, response.code()+"=="+response.headers().toString());
		if (response.isSuccessful()) {
			Message message = Message.obtain();
			message.what = CALLBACK_SUCCESSFUL;
			message.obj = response.body().string();
			mHandler.sendMessage(message);
		} else {
			Message message = Message.obtain();
			message.what = CALLBACK_FAILED;
			message.obj = "未知异常，请重试";
			mHandler.sendMessage(message);
		}
	}

	/**
	 * 请求成功
	 *
	 * @param response
	 */
	public void onSuccess(String response) {
	}

	/**
	 * 请求异常
	 *
	 * @param error
	 */
	public void onError(String error) {
	}

	/**
	 * 请求结束
	 */
	public void onEnd() {
	}
}
